import 'dart:async';
import 'dart:io';

import 'package:flutter_deer/objectbox.g.dart';
import 'package:injectable/injectable.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';


@singleton
class ObjectIdBox {
  late Store _store;
  final Completer<Store> _storeCompleter = Completer();

  Store get store {
    return _store;
  }

  Future<void> initStore() async {
    final directory = await getApplicationDocumentsDirectory();
    // 构建 ObjectBox 数据库目录路径
    final String objectBoxPath = path.join(directory.path, 'objectbox');
    _store = await openStore(directory: objectBoxPath);
    _storeCompleter.complete(_store);
    print('ObjectIdBox initStore: ${_store.directoryPath}');
  }

  Future<Store> get storeAsync => _storeCompleter.future;

  void dispose() {
    // store.close();
  }

  /// 删除 ObjectBox 数据库
  Future<void> deleteObjectBoxDatabase() async {
    // 获取应用的文档目录
    final Directory documentDir = await getApplicationDocumentsDirectory();

    // 构建 ObjectBox 数据库目录路径
    final String objectBoxPath = path.join(documentDir.path, 'objectbox');

    // 检查目录是否存在
    final Directory objectBoxDir = Directory(objectBoxPath);
    if (objectBoxDir.existsSync()) {
      // 删除整个 objectbox 目录及其所有内容
      objectBoxDir.deleteSync(recursive: true);
      print('ObjectBox 数据库已删除: $objectBoxPath');
    } else {
      print('ObjectBox 数据库不存在: $objectBoxPath');
    }
  }
}
